import { dictGetAll } from '@/config/api/common/api';
import { $Http } from '@/config/service/http';
import dictionary from '@/filters/dictionary';
import { formInfoStore } from '@/store/modules/form';

export const getDictionaryList = (state, fn = null) => {
  const formStore = formInfoStore();
  let dictionaryData = formStore.getDictionary;
  console.log('数据字典aaa', state);

  if (dictionaryData[state?.filterName]) {
    if (fn) {
      fn(dictionaryData[state.filterName]);
    }
  } else if (state.url) {
    $Http.api(state.url, state.params ? state.params : { pageSize: 500 }, state.protType ? state.protType : 'get').then((res: any) => {
      if (res.success) {
        // 循环子层级
        const arr = getTreeData(res.data, state);
        if( fn ){
          fn(arr)
        }
      }
    });
  }
};

//返回数据字典options配置
export const getDictionaryOptions = (state)=>{
  const formStore = formInfoStore();
  let dictionaryData = formStore.getDictionary;
  let dicObj: any = dictionaryData[state.filterName] || dictionary[state.filterName];
  let arr: any = [];
  for (const key in dicObj) {
    if (dicObj.hasOwnProperty(key)) {
      arr.push({
        label: dicObj[key],
        value: state.valueType === 'string' ? key + '' : +key
      });
    }
  }
  return arr
}

//请求数据字典
export const setDictionaryList = () => {
  const formStore = formInfoStore();
  dictGetAll().then((res) => {
    if (res && res.data) {
      Object.assign(dictionary, res.data || {});
      formStore.setDictionary(dictionary);
    }
  });
};

// 树形选择，子层级数据
export function getTreeData(list: any[], state) {
  if (!list) {
    return [];
  }
  return list.map((item: any) => {
    const obj: any = { ...item, label: item[state.nameKey], value: item[state.nameValue] };
    const levelOpt = state.childrenLevel;
    if (levelOpt && obj[levelOpt.nameChildren]) {
      obj.children = obj[levelOpt.nameChildren].map((levItem) => ({ label: levItem[levelOpt.nameKey], value: levItem[levelOpt.nameValue] }));
      const levChildren = getTreeData(item[state.nameChildren], state);
      obj.children.push(...levChildren);
    } else if (item[state.nameChildren] && item[state.nameChildren].length > 0) {
      obj.children = getTreeData(item[state.nameChildren], state);
    }
    return obj;
  });
}